package com.dcy.daily.skill.rabbitMQ.official.rpc;

import com.dcy.daily.skill.rabbitMQ.official.utils.MQConnectUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.nio.charset.StandardCharsets;

/**
 * 使用MQ来实现RPC功能
 * 服务端接收客户端发过来的数字，将该数字斐波那契值返回给客户端
 *
 * @author duanchunyu
 * @version 1.0.0
 * @createTime 2021年07月21日 09:57
 */
public class RPCServer {
    private static final String RPC_QUEUE_NAME = "rpc_queue";

    private static int fib(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        return fib(n - 1) + fib(n - 2);
    }

    public static void main(String[] args) throws Exception {
        Connection connection = MQConnectUtil.getConnection();
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        //队列清除
        channel.queuePurge(RPC_QUEUE_NAME);
        //不向繁忙的队列发送消息，保证公平分配
        channel.basicQos(1);
        System.out.println(" [x] Awaiting RPC requests");
        Object monitor = new Object();

        channel.basicConsume(RPC_QUEUE_NAME, (consumerTag, delivery) -> {
            AMQP.BasicProperties replyProps = new AMQP.BasicProperties()
                    .builder()
                    .correlationId(delivery.getProperties().getCorrelationId())
                    .build();
            String response = "";
            try {
                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                int n = Integer.parseInt(message);
                System.out.println(" [.] fib(" + message + ")");
                response += fib(n);
            } catch (RuntimeException e) {
                System.out.println(" [.] " + e.toString());
            } finally {
                channel.basicPublish("", delivery.getProperties().getReplyTo(), replyProps, response.getBytes(StandardCharsets.UTF_8));
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                // RabbitMq consumer worker thread notifies the RPC server owner thread
                synchronized (monitor) {
                    monitor.notify();
                }
            }
        }, consumerTag -> {
        });

        // Wait and be prepared to consume the message from RPC client.
        while (true) {
            synchronized (monitor) {
                try {
                    monitor.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
